package com.shivandragon.jGameLoopStudy.basicFixedStepGameLoop;

import java.awt.image.BufferedImage;

import com.shivandragon.jGameLoopStudy.common.BallClockTools;


public class BasicFixedGameEntity {


    private BufferedImage[] animationImages;
    
    private int currentAnimationImageIdx;
    private int loopsSinceLastImageIdxChanged;
    
    private int startX, startY;
    private int width, height;
    
    private final String tag;
    
    private boolean simulateUpdateDelay;
    
    private final int updatesInASecond;
    
    private BasicFixedDebug debugger;
    
    public BasicFixedGameEntity(String tag, int startX, int startY, int width, int height, boolean simulateUpdateDelay) {
        animationImages = BallClockTools.loadAnimationImages();
        this.startX = startX;
        this.startY = startY;
        this.width = width;
        this.height = height;
        this.tag = tag;
        this.updatesInASecond = 1000/BasicFixedGameLoop.FIXED_STEP_IDEAL_DURATION_MS;
        debugger = new BasicFixedDebug();
        this.simulateUpdateDelay = simulateUpdateDelay;
    }
    
    public BasicFixedGameEntity(String tag, int startX, int startY, int width, int height) {
        this(tag, startX, startY, width, height, false);
    }
    
    public void update() {
        loopsSinceLastImageIdxChanged = loopsSinceLastImageIdxChanged+1;
        if(loopsSinceLastImageIdxChanged==updatesInASecond) {
            currentAnimationImageIdx++;
            currentAnimationImageIdx = currentAnimationImageIdx%10;//wrap animation around
            loopsSinceLastImageIdxChanged=0;
        }
        
        debugger.debug(tag, currentAnimationImageIdx);
    }
    
    Sprite getCurrentSprite() {
        if(simulateUpdateDelay && currentAnimationImageIdx==7) {
            try {
                Thread.sleep(40);
            } catch(Throwable t) {}
        }
        return new Sprite(this.startX, this.startY,
            this.width, this.height,
            animationImages[currentAnimationImageIdx]);
    }
    
    public class Sprite {
        public final int x,y,width,height;
        public final BufferedImage image;
        
        public Sprite(int x, int y, int width, int height, BufferedImage image) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            this.image = image;
        }        
    }
    
}
